from machine import I2C, Pin
import time

i2c = I2C(0, scl=Pin(5), sda=Pin(4), freq=100000)  # 使用GPIO4/5
GW_GRAY_ADDR = 0x4C

def ping_sensor():
    timeout = time.ticks_add(time.ticks_ms(), 5000)
    while time.ticks_diff(timeout, time.ticks_ms()) > 0:
        try:
            i2c.writeto(GW_GRAY_ADDR, b'\xAA')
            status = i2c.readfrom(GW_GRAY_ADDR, 1)
            if status[0] == 0x66:
                return True
        except OSError:
            pass
        time.sleep_ms(10)
    print("Ping timeout")
    return False

def setup():
    if not ping_sensor():
        raise RuntimeError("Sensor init failed")
    i2c.writeto(GW_GRAY_ADDR, b'\xD0')
    print("Sensor ready")

def read_rgb():
    data = i2c.readfrom(GW_GRAY_ADDR, 24)
    return data[0], data[1], data[2]

setup()
while True:
    r, g, b = read_rgb()
    print(f"R:{r} G:{g} B:{b}")
    time.sleep(0.5)